﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using FlitBit.Copy;
using FlitBit.Core;
using FlitBit.Dto.ModelBinding.Sample.Models;

namespace FlitBit.Dto.ModelBinding.Sample.Controllers
{
	public class PeepsController : Controller
	{
		// Since we are only concerned with the ability to bind to DTOs we'll
		// use a static list as a data store; THIS TECHNIQUE IS FOR DEMO PURPOSES ONLY!
		static readonly List<IPerson> __peeps = new List<IPerson>();

		static readonly ICopier<IPerson, IPerson> __copier =
			FactoryProvider.Factory.CreateInstance<ICopier<IPerson, IPerson>>();

		//
		// GET: /Peeps/

		public ActionResult Index()
		{
			var peeps = from p in __peeps
									orderby p.Name
									select p;
			return View(peeps);
		}

		//
		// GET: /Peeps/Details/5

		public ActionResult Details(int id)
		{
			var peep = __peeps.FirstOrDefault(p => p.ID == id);
			return View(peep ?? FactoryProvider.Factory.CreateInstance<IPerson>());
		}

		//
		// GET: /Peeps/Create

		public ActionResult Create() { return View(); }

		//
		// POST: /Peeps/Create

		[HttpPost]
		public ActionResult Create(IPerson person)
		{
			try
			{
				person.ID = __peeps.Count;
				__peeps.Add(person);
				return RedirectToAction("Index");
			}
			catch
			{
				return View();
			}
		}

		//
		// GET: /Peeps/Edit/5

		public ActionResult Edit(int id)
		{
			var peep = __peeps.FirstOrDefault(p => p.ID == id);
			if (peep == null)
			{
				return RedirectToAction("Index");
			}
			return View(peep);
		}

		//
		// POST: /Peeps/Edit/5

		[HttpPost]
		public ActionResult Edit(int id, IPerson person)
		{
			try
			{
				var peep = __peeps.FirstOrDefault(p => p.ID == id);
				if (peep != null)
				{
					__copier.CopyTo(peep, person, CopyKind.Loose, FactoryProvider.Factory);
				}
				return RedirectToAction("Index");
			}
			catch
			{
				return View();
			}
		}

		//
		// GET: /Peeps/Delete/5

		public ActionResult Delete(int id)
		{
			var peep = __peeps.FirstOrDefault(p => p.ID == id);
			if (peep == null)
			{
				return RedirectToAction("Index");
			}
			return View(peep);
		}

		//
		// POST: /Peeps/Delete/5

		[HttpPost]
		public ActionResult Delete(int id, IPerson person)
		{
			try
			{
				var peep = __peeps.FirstOrDefault(p => p.ID == id);
				if (peep != null)
				{
					__peeps.Remove(peep);
				}
				return RedirectToAction("Index");
			}
			catch
			{
				return View();
			}
		}
	}
}